<?php
/**
 * Created by PhpStorm.
 * @author WYZ <wyz@jungo.com.cn>
 * @copyright 深圳市俊网网络有限公司
 */

namespace Selibra\ORM;


use Selibra\Tools\Console;
use Selibra\Di\DI;
use Selibra\Model\SFModel;
use Selibra\ORM\Protocols\SubTableInterface;

class TableManager
{

    /**
     * @var SFModel
     */
    protected $dao;


    /**
     * @var string
     */
    protected ?string $tableName = null;

    /**
     * @var SubTableInterface
     */
    protected SubTableInterface $subTableObject;

    public function __construct($dao)
    {
        $this->dao = $dao;
    }

    /**
     * @param $daoClass
     * @param null $entity
     * @return mixed|string
     */
    public function getDaoTable()
    {
        $daoClass = get_class($this->dao);
        $tableName = TableCollector::get($daoClass);
        if (empty($tableName)) {
            return null;
        }
        $this->tableName = $tableName;
        if (class_exists($this->tableName)) {
            $this->tableName = $this->getSubTable()->getTableName($this->dao->getEntity());
            // 生成表
            $this->genTable();
        }
        return $this->tableName;
    }


    /**
     * 生成表
     * @return void
     */
    public function genTable()
    {
        $createSubTableSql = $this->getSubTable()->getCreateSubTableSql($this->tableName);
        TableCreator::createTable($this->dao, $createSubTableSql);
    }


    /**
     * @return mixed|object|SubTableInterface|null
     */
    protected function getSubTable()
    {
        if (!isset($this->subTableObject)) {
            $this->subTableObject = DI::getObjectContext($this->tableName);
        }
        return $this->subTableObject;
    }

}